package api

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"zhonghui/console/warehouse/cfgx"
	"zhonghui/console/warehouse/respx"
)

func (server *Server) Sts(c *gin.Context) {
	client, err := sts.NewClientWithAccessKey("cn-chengdu",
		cfgx.Cfg().GetString("oss.sts.access_key_id"),
		cfgx.Cfg().GetString("oss.sts.access_key_secret"),
	)
	if err != nil {
		respx.Error(c, "获取临时上传凭证错误", err)
		return
	}

	req := sts.CreateAssumeRoleRequest()
	req.Scheme = "https"
	req.RoleArn = "acs:ram::1982060208802975:role/aliyunosstokengeneratorrole"
	req.DurationSeconds = requests.NewInteger(3600)
	req.RoleSessionName = "external-username"
	req.Method = "POST"

	resp, err := client.AssumeRole(req)
	if err != nil {
		respx.Error(c, "获取临时上传凭证错误", err)
		return
	}

	if !resp.IsSuccess() {
		respx.Error(c, "获取临时上传凭证错误", err)
		return
	}

	respx.Success(c, resp, nil)
}

func (server *Server) Sign(c *gin.Context) {
	req := struct {
		ObjectPath string `json:"object_path"`
	}{}
	if err := c.ShouldBindJSON(&req); err != nil {
		respx.Bad(c, err)
		return
	}

	cc, _ := oss.New(
		"https://"+cfgx.Cfg().GetString("oss.end_point"),
		cfgx.Cfg().GetString("oss.access_key_id"),
		cfgx.Cfg().GetString("oss.access_key_secret"),
		oss.UseCname(false),
	)
	b, _ := cc.Bucket(cfgx.Cfg().GetString("oss.bucket"))

	signUrl, _ := b.SignURL(req.ObjectPath, oss.HTTPPut, 60)

	resp := struct {
		SignUrl string `json:"sign_url"`
	}{SignUrl: signUrl}

	respx.Success(c, resp, nil)
}
